package github.saw96x.remoting.transport.netty.client;

import github.saw96x.common.enums.CompressTypeEnum;
import github.saw96x.common.enums.SerializationTypeEnum;
import github.saw96x.common.extension.ExtensionLoader;
import github.saw96x.common.factory.SingletonFactory;
import github.saw96x.registry.ServiceDiscovery;
import github.saw96x.remoting.constants.RpcConstants;
import github.saw96x.remoting.pojo.RpcMessage;
import github.saw96x.remoting.pojo.RpcRequest;
import github.saw96x.remoting.pojo.RpcResponse;
import github.saw96x.remoting.transport.RpcRequestTransport;
import github.saw96x.remoting.transport.netty.codec.RpcMessageDecoder;
import github.saw96x.remoting.transport.netty.codec.RpcMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author Saw96x
 * @date 2022/3/18 9:00
 */
@Slf4j
public final class NettyRpcClient implements RpcRequestTransport {
  private final ServiceDiscovery serviceDiscovery;
  private final UnprocessedRequests unprocessedRequests;
  private final ChannelProvider channelProvider;
  private final Bootstrap bootstrap;
  private final EventLoopGroup eventLoopGroup;

  public NettyRpcClient() {
    // 初始化线程组资源
    eventLoopGroup = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO))
        //  超时连接
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            // 如果15秒内未发送请求，则维持五秒周期的心跳保持连接
            p.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
            p.addLast(new RpcMessageEncoder());
            p.addLast(new RpcMessageDecoder());
            p.addLast(new NettyRpcClientHandler());
          }
        });
    this.serviceDiscovery = ExtensionLoader.getExtensionLoader(ServiceDiscovery.class).getExtension("zk");
    this.unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
    this.channelProvider = SingletonFactory.getInstance(ChannelProvider.class);
  }

  /**
   * 连接服务器并获取channel对象
   *
   * @param inetSocketAddress 服务器地址
   * @return channel
   */
  @SneakyThrows
  public Channel doConnect(InetSocketAddress inetSocketAddress) {
    CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
    bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
      if (future.isSuccess()) {
        log.info("The client has connected [{}] successful!", inetSocketAddress.toString());
        completableFuture.complete(future.channel());
      } else {
        throw new IllegalStateException();
      }
    });
    return completableFuture.get();
  }

  @Override
  public Object sendRpcRequest(RpcRequest rpcRequest) {
    // 返回对象
    CompletableFuture<RpcResponse<Object>> resultFuture = new CompletableFuture<>();
    // 获取服务端地址
    InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest);
    // 获取地址的channel
    Channel channel = getChannel(inetSocketAddress);
    if (channel.isActive()) {
      // put未处理请求
      unprocessedRequests.put(rpcRequest.getRequestId(), resultFuture);
      RpcMessage rpcMessage = RpcMessage.builder().data(rpcRequest)
          .codec(SerializationTypeEnum.HESSIAN.getCode())
          .compress(CompressTypeEnum.GZIP.getCode())
          .messageType(RpcConstants.REQUEST_TYPE).build();
      channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
          log.info("client send message: [{}]", rpcMessage);
        } else {
          future.channel().close();
          resultFuture.completeExceptionally(future.cause());
          log.error("Send failed:", future.cause());
        }
      });
    } else {
      throw new IllegalStateException();
    }

    return resultFuture;
  }

  public Channel getChannel(InetSocketAddress inetSocketAddress) {
    Channel channel = channelProvider.get(inetSocketAddress);
    if (channel == null) {
      channel = doConnect(inetSocketAddress);
      channelProvider.set(inetSocketAddress, channel);
    }
    return channel;
  }

  public void close() {
    eventLoopGroup.shutdownGracefully();
  }
}
